<?php
/*
 * @Description    : 消息推送数据预处理任务
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-01-22 15:56:35
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-05-09 10:51:10
 */

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use App\Common\RedisCache;
use App\Service\Common;
use Yurun\Util\HttpRequest;

class PushFeedbackJob
{
    public $params;
    public $redisCache;
    public $http;

    public function __construct($params)
    {
        $this->params = $params;
        $this->redisCache = new RedisCache;
        $this->http = new HttpRequest;
    }

    public function handle()
    {
        if (!empty($this->params) && is_array($this->params)) {
            $commonService = new Common;
            $logData = $this->params['logData'];
            $logData['log_field'] = [];
            foreach ($this->params['logData'] as $key => $vo) {
                $logData['log_field'][] = $key;
            }
            $logData['user_id'] = isset($this->params['user_id']) && !empty($this->params['user_id']) ? $this->params['user_id'] : '';
            $logData['fsi_id'] = $this->params['fsi_id'];
            $logData['tag_type'] = $this->params['tag_type'];
            $logData['remote_ip'] = $this->params['param']['remote_ip'];
            $logData['remote_ip_area'] = $commonService->ip2Region($this->params['param']['remote_ip']);
            $this->params['param']['remote_ip_area'] = $logData['remote_ip_area'];
            $logData['uid'] = (int)$this->params['serverInfo']['uid'];
            $logData['username'] = (int)$this->params['serverInfo']['username'];
            $logData['create_time'] = time();
            $logData['delete_time'] = time() + intval($this->params['serverInfo']['save_day']) * 86400;
            $logData['date'] = date('Y-m-d');
            $logData['only_hour'] = date('H') . ':00';
            $logData['_id'] = isset($this->params['f_id'])? $this->params['f_id']:createId('F');
            // mongodb2()->site_log->insertOne($logData);
            $collection = mongodb2()->selectCollection('feedback_log');
            $collection->insertOne($logData);
            $commonService->mongodbIndexCreate($collection, 'uid_create_req_fsiid', ['uid' => 1, 'create_time' => -1, 'request_id' => -1, 'fsi_id' => -1]);
            $commonService->mongodbIndexCreate($collection, 'uid_create_req_fsiid2', ['uid' => 1, 'create_time' => -1, 'fsi_id' => -1]);
            unset($collection);
            if (isset($this->params['serverInfo']['notice_open']) && $this->params['serverInfo']['notice_open'] == 1 && isset($this->params['serverInfo']['ps_id']) && !empty($this->params['serverInfo']['ps_id'])) {
                $pushServerInfo = $this->redisCache->getPushServer($this->params['serverInfo']['ps_id']);
                $ignoreThis = 0;
                if (isset($this->params['serverInfo']['notice_params_ignore']) && !empty($this->params['serverInfo']['notice_params_ignore'])) {
                    $browserParamsArr = explode("\n", $this->params['serverInfo']['notice_params_ignore']);
                    foreach ($browserParamsArr as $vo) {
                        $browserVoArray = explode('=', $vo);
                        if (count($browserVoArray) >= 2) {
                            if (isset($this->params['logData'][$browserVoArray[0]]) && strstr($this->params['logData'][$browserVoArray[0]], $browserVoArray[1]) != false && $ignoreThis == 0) {
                                $ignoreThis = 1;
                            }
                        }
                    }
                    unset($browserParamsArr, $browserVoArray, $vo);
                }
                if (!empty($pushServerInfo) && $ignoreThis == 0) {
                    $userSettingInfo = $this->redisCache->getUserSettingByUid($this->params['serverInfo']['uid']);
                    $pushData['dev_key'] = $userSettingInfo['dev_key'];
                    unset($userSettingInfo);
                    $pushData['ps_id'] = $this->params['serverInfo']['ps_id'];
                    $pushData['title'] = '【新反馈】- ' . $this->params['serverInfo']['title'];
                    $pushData['msg_type'] = 'markdown';
                    $pushData['atMobiles'] = $this->params['atMobiles'];
                    $contentNotice = '';
                    $markdownNotice = '';
                    if (isset($this->params['serverInfo']['notice_params']) && !empty($this->params['serverInfo']['notice_params'])) {
                        $noticeArray = explode('|', $this->params['serverInfo']['notice_params']);
                        if (!empty($noticeArray)) {
                            foreach ($noticeArray as $key) {
                                if (isset($this->params['param'][$key])) {
                                    $keyName = (isset($this->params['serverInfo']['fieldsName'][$key]) && !empty($this->params['serverInfo']['fieldsName'][$key])) ? $this->params['serverInfo']['fieldsName'][$key] : $key;
                                    if ($key == 'remote_ip') {
                                        $contentNotice .= '来源IP: ' . $this->params['param'][$key] . '(' . $this->params['param']['remote_ip_area'] . ')<br />';
                                        $markdownNotice .= " \n> **来源IP：**" . $this->params['param'][$key] . '(' . $this->params['param']['remote_ip_area'] . ')';
                                    } else {
                                        $contentNotice .= $keyName . ': ' . $this->params['param'][$key] . '<br />';
                                        $value = is_numeric($this->params['param'][$key]) ? '[' . $this->params['param'][$key] . '](tel:' . $this->params['param'][$key] . ')' : $this->params['param'][$key];
                                        $markdownNotice .= " \n> **{$keyName}：**" . $value;
                                    }
                                }
                            }
                        }
                    }
                    if (!empty($markdownNotice)) {
                        $markdownNotice .= "\n> **反馈时间：**" . date('Y-m-d H:i:s') ."\n> \n> **[温馨提示]** 详情可 [前往柠聚开发平台查看](http://console.21ds.cn/feedback/FeedbackLog?site_id={$this->params['fsi_id']})";
                    }
                    $pushData['content'] = '【新反馈】- ' . $this->params['serverInfo']['title'] . '<br />' . $contentNotice . '请<a href="http://console.21ds.cn/feedback/FeedbackLog'. $this->params['fsi_id'].'">前往柠聚开发平台查看</a>。';
                    $pushData['msg_content'] = "#### 【新反馈】- {$this->params['serverInfo']['title']} \n> **反馈详情** \n> {$markdownNotice}";
                    $commonService->doSendPush($pushData, $pushServerInfo['server_secret']);
                }
            }
            
            if (isset($this->params['serverInfo']['accept_next']) && $this->params['serverInfo']['accept_next'] == 1 && isset($this->params['serverInfo']['accept_next_type'])) {
                if (in_array(1, $this->params['serverInfo']['accept_next_type']) && isset($this->params['serverInfo']['accept_sms_phone']) && !empty($this->params['serverInfo']['accept_sms_phone']) && isset($this->params['serverInfo']['accept_sms_sid']) && !empty($this->params['serverInfo']['accept_sms_sid']) && isset($this->params['serverInfo']['accept_sms_tid']) && !empty($this->params['serverInfo']['accept_sms_tid'])) {
                    $smsServerInfo = $this->redisCache->getSmsServer($this->params['serverInfo']['accept_sms_sid']);
                    $userSettingInfo = $this->redisCache->getUserSettingByUid($this->params['serverInfo']['uid']);
                    $pushData['dev_key'] = $userSettingInfo['dev_key'];
                    $pushData['ss_id'] = $this->params['serverInfo']['accept_sms_sid'];
                    $pushData['st_id'] = $this->params['serverInfo']['accept_sms_tid'];
                    $phoneList = [];
                    $sms_phone = explode(',', $this->params['serverInfo']['accept_sms_phone']);
                    foreach ($sms_phone as $key => $vo) {
                        if (isset($logData[$vo])) {
                            $phoneList[] = $logData[$vo];
                        }elseif($commonService->validatePhoneNumber($vo)){
                            $phoneList[] = $vo;
                        }
                    }
                    $pushData['phone'] = implode(',', $phoneList);
                    $paramJson = [];
                    if (isset($this->params['serverInfo']['accept_sms_param']) && !empty($this->params['serverInfo']['accept_sms_param'])) {
                        $sms_param = json_decode($this->params['serverInfo']['accept_sms_param'], true);
                        if (!empty($sms_param)) {
                            foreach ($sms_param as $key => $vo) {
                                if (isset($logData[$vo])) {
                                    $paramJson[$key] = $logData[$vo];
                                }else{
                                    $paramJson[$key] = $vo;
                                }
                            }
                        }
                    }
                    $pushData['params_json'] = json_encode($paramJson);
                    $commonService->smsSend($pushData, $smsServerInfo);
                }
                if (in_array(2, $this->params['serverInfo']['accept_next_type']) && isset($this->params['serverInfo']['accept_email_sid'])) {
                    $smsServerInfo = $this->redisCache->getEmailServer($this->params['serverInfo']['accept_email_sid']);
                    $userSettingInfo = $this->redisCache->getUserSettingByUid($this->params['serverInfo']['uid']);
                    $pushData['dev_key'] = $userSettingInfo['dev_key'];
                    $pushData['es_id'] = $this->params['serverInfo']['accept_email_sid'];
                    $pushData['title'] = $this->params['serverInfo']['title'];
                    $pushData['et_id'] = isset($this->params['serverInfo']['accept_email_tid']) && !empty($this->params['serverInfo']['accept_email_tid']) ? $this->params['serverInfo']['accept_email_tid'] : '';
                    $phoneList = [];
                    $sms_phone = explode(',', $this->params['serverInfo']['accept_email_email']);
                    foreach ($sms_phone as $key => $vo) {
                        if (isset($logData[$vo])) {
                            $phoneList[] = $logData[$vo];
                        } elseif ($commonService->validateEmail($vo)) {
                            $phoneList[] = $vo;
                        }
                    }
                    $pushData['email'] = implode(',', $phoneList);
                    if (isset($this->params['serverInfo']['accept_email_param']) && !empty($this->params['serverInfo']['accept_email_param'])) {
                        $sms_param = json_decode($this->params['serverInfo']['accept_email_param'], true);
                        if (!empty($sms_param)) {
                            foreach ($sms_param as $key => $vo) {
                                if (isset($logData[$vo])) {
                                    $pushData[$key] = $logData[$vo];
                                } else {
                                    $pushData[$key] = $vo;
                                }
                            }
                        }
                    }
                    $tr_td = '';
                    foreach ($this->params['logData'] as $key => $vo) {
                        $tr_td .= '<tr><td>' . $key . '</td><td>' . $vo . '</td></tr>';
                    }
                    $htmlContent = '<table><tr>
        <th>参数名</th>
        <th>值</th>
    </tr>'. $tr_td. '</table><style>
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    th {
        background-color: #f2f2f2;
    }
    tr:nth-child(even) {
        background-color: #f9f9f9;
    }
    tr:nth-child(odd) {
        background-color: #ffffff;
    }
</style>';
                    $pushData['content'] = $htmlContent;
                    $commonService->emailSend($pushData, $smsServerInfo);
                }
                if (in_array(3, $this->params['serverInfo']['accept_next_type']) && isset($this->params['serverInfo']['accept_next_url']) && !empty($this->params['serverInfo']['accept_next_url'])) {
                    $this->http->post($this->params['serverInfo']['accept_next_url'], $logData);
                }
            }
            unset($pushServerInfo, $contentNotice, $markdownNotice, $smsServerInfo, $userSettingInfo);
        }
        unset($pushData, $commonService,$logData,$this->params);
    }
}
